package com.example.videoviewtest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.WindowInsets;
import android.widget.Toast;
import android.widget.VideoView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private VideoView videoView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().getInsetsController().hide(WindowInsets.Type.statusBars());
        videoView = findViewById(R.id.vv);
        String file_path=getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString()+"/video";

        Deposit(file_path,"test.mp4");

        //使用VideoView播放视频
        String path=file_path+"/test.mp4";
        Log.d("播放地址",path);
        videoView.setVideoPath(path);



        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        videoView.setVisibility(View.VISIBLE);

                    }
                });
                videoView.start();

            }
        };
        timer.schedule(timerTask, 3000);

    }

    //将assets内文件存储到本地下载目录
    public Boolean Deposit(String path,String fileName){
        InputStream inputStream;
        try {

            //判断文件是否存在
            File file1=new File(path + "/" + fileName);

            if(!file1.exists()){

                inputStream=getAssets().open(fileName);
                File file = new File(path);
                //当目录不存在时创建目录
                if(!file.exists()){
                    file.mkdirs();
                }

                FileOutputStream fileOutputStream = new FileOutputStream(path + "/" + fileName);// 保存到本地的文件夹下的文件
                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = inputStream.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, count);
                }
                fileOutputStream.flush();
                fileOutputStream.close();
                inputStream.close();

            }

            return true;


        }catch (IOException e){
            e.printStackTrace();
        }
        return false;
    }

}
